<template>
  <div class="goods-detail-container">
    <!-- 面包屑导航 -->
    <div class="breadcrumb">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>商品详情</el-breadcrumb-item>
        <el-breadcrumb-item>{{ goods?.name }}</el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <!-- 商品主区域 -->
    <div class="goods-main">
      <!-- 左侧图片区域 -->
      <div class="goods-gallery">
        <div class="main-image">
          <el-image 
            :src="goods?.image" 
            :preview-src-list="[goods?.image]"
            fit="contain"
            class="goods-main-image"
          />
          <div class="image-tag hot" v-if="goods?.is_hot">热销</div>
          <div class="image-tag new" v-if="goods?.is_new">新品</div>
        </div>
      </div>

      <!-- 右侧商品信息 -->
      <div class="goods-info">
        <h1 class="goods-title">{{ goods?.name }}</h1>
        <div class="goods-desc">{{ goods?.description }}</div>
        
        <!-- 价格区域 -->
        <div class="price-section">
          <div class="current-price">
            <span class="price-label">惊喜价</span>
            <span class="price-symbol">¥</span>
            <span class="price-number">{{ goods?.discounted_price }}</span>
          </div>
          <div class="original-price">
            原价: <span class="line-through">¥{{ goods?.price }}</span>
          </div>
          <div class="save-amount" v-if="goods?.price && goods?.discounted_price && goods.price - goods.discounted_price > 0">
            立省 ¥{{ (goods.price - goods.discounted_price).toFixed(2) }}
          </div>
        </div>

        <!-- 服务保障 -->
        <div class="service-section">
          <div class="service-item">
            <span class="service-icon">✓</span>
            <span>正品保证</span>
          </div>
          <div class="service-item">
            <span class="service-icon">✓</span>
            <span>七天无理由退货</span>
          </div>
          <div class="service-item">
            <span class="service-icon">✓</span>
            <span>全国联保</span>
          </div>
        </div>

        <!-- 库存和选择 -->
        <div class="selection-section">
          <div class="stock-info">
            <span class="stock-label">库存</span>
            <span class="stock-count">{{ goods?.stock }}件</span>
          </div>
          
          <div class="quantity-selector">
            <span class="quantity-label">数量</span>
            <div class="quantity-control">
              <el-input-number 
                v-model="buyCount"
                :min="0"
                :max="goods?.stock"
                controls-position="right"
                size="large"
              />
              <span class="stock-tips">剩余{{ goods?.stock }}件</span>
            </div>
          </div>
        </div>

        <!-- 操作按钮 - 只保留加入购物车 -->
        <div class="action-buttons">
          <el-button 
            type="primary" 
            size="large" 
            class="btn-cart"
            :disabled="buyCount === 0"
            @click="addToCar"
          >
            <i class="el-icon-shopping-cart"></i>
            加入购物车
          </el-button>
        </div>

        <!-- 促销信息 -->
        <div class="promotion-section">
          <div class="promotion-title">促销活动</div>
          <div class="promotion-item">
            <span class="promotion-tag">满减</span>
            <span>满300元减30元</span>
          </div>
          <div class="promotion-item">
            <span class="promotion-tag">优惠</span>
            <span>新用户首单立减20元</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 商品详情和评价 - 调整高度 -->
    <div class="goods-detail-tabs">
      <el-tabs v-model="activeTab" class="detail-tabs">
        <el-tab-pane label="商品详情" name="detail">
          <div class="detail-content">
            <div v-html="goods?.detail" class="editor-content-view"></div>
          </div>
        </el-tab-pane>
        
        <el-tab-pane label="商品评价" name="evaluation">
          <div class="evaluation-section">
            <!-- 评价概览 -->
            <div class="evaluation-overview" v-if="evaluations.length > 0">
              <div class="overview-item">
                <div class="overview-value">{{ averageRating }}</div>
                <div class="overview-label">综合评分</div>
              </div>
              <div class="overview-item">
                <div class="overview-value">{{ positiveRate }}%</div>
                <div class="overview-label">好评率</div>
              </div>
              <div class="overview-item">
                <div class="overview-value">{{ totalEvaluations }}</div>
                <div class="overview-label">评价数</div>
              </div>
            </div>

            <!-- 评价列表 -->
            <div class="evaluation-list">
              <el-empty description="暂无评价" v-show="evaluations.length == 0"/>
              <div v-for="(item, index) in evaluations" :key="index" class="evaluation-item">
                <div class="evaluation-header">
                  <div class="user-info">
                    <el-avatar :size="40" :src="getUserAvatar(item.user)" class="user-avatar">
                      {{ item.user.username.charAt(0) }}
                    </el-avatar>
                    <div class="user-detail">
                      <div class="username">{{ item.user.username }}</div>
                      <el-rate 
                        v-model="item.star" 
                        disabled 
                        size="small"
                        class="evaluation-rate"
                      />
                    </div>
                  </div>
                  <div class="evaluation-time">{{ formatTime(item.created_at) }}</div>
                </div>
                <div class="evaluation-content">{{ item.content }}</div>
                <div class="evaluation-actions">
                  <span class="action-item">👍 有用 ({{ getEvaluationLikes(item) }})</span>
                  <span class="action-item">💬 回复</span>
                </div>
              </div>
              
              <!-- 加载更多 -->
              <div v-show="hasMore" class="load-more" @click="loadEvaluations">
                <el-button type="text" :loading="loadingMore">
                  {{ loadingMore ? '加载中...' : '点击加载更多' }}
                </el-button>
              </div>
            </div>
          </div>
        </el-tab-pane>
        
        <el-tab-pane label="规格参数" name="specs">
          <div class="specs-section" v-if="goods?.specifications">
            <div v-for="(spec, key) in goods.specifications" :key="key" class="spec-item">
              <span class="spec-label">{{ key }}：</span>
              <span class="spec-value">{{ spec }}</span>
            </div>
          </div>
          <el-empty v-else description="暂无规格参数" />
        </el-tab-pane>
      </el-tabs>
    </div>

    <!-- 回到顶部 -->
    <el-backtop target=".goods-detail-container" :bottom="100" />
  </div>
</template>
<script setup lang="ts">
import { onMounted, ref, computed } from 'vue';
import { EvaluationItemData, RequestPath, startRequest } from '../base/RequestWork';
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';
import Account from '../base/AccountStore';

// 扩展类型定义
interface EvaluationUser {
  username: string;
  id: number;
  role: string;
  avatar?: string;
}

interface ExtendedEvaluationItemData extends EvaluationItemData {
  user: EvaluationUser;
  likes?: number;
}

// 现有逻辑保持不变
const props = defineProps(['id'])
let goods = ref()
let evaluations = ref<ExtendedEvaluationItemData[]>([])
let limit = 2
let hasMore = ref(true)
let buyCount = ref(0)
let account = Account()
let router = useRouter()

// 新增响应式数据
const activeTab = ref('detail')
const loadingMore = ref(false)

// 计算属性
const totalEvaluations = computed(() => evaluations.value.length)

// 计算平均评分
const averageRating = computed(() => {
  if (evaluations.value.length === 0) return '0.0'
  const total = evaluations.value.reduce((sum, item) => sum + item.star, 0)
  return (total / evaluations.value.length).toFixed(1)
})

// 计算好评率
const positiveRate = computed(() => {
  if (evaluations.value.length === 0) return '0'
  const positiveCount = evaluations.value.filter(item => item.star >= 4).length
  return Math.round((positiveCount / evaluations.value.length) * 100)
})

// 新增方法
const formatTime = (timeStr: string) => {
  return new Date(timeStr).toLocaleDateString()
}

// 安全访问用户头像
const getUserAvatar = (user: EvaluationUser) => {
  return user.avatar || ''
}

// 安全访问点赞数
const getEvaluationLikes = (evaluation: ExtendedEvaluationItemData) => {
  return evaluation.likes || 0
}

// 添加加载状态
function loadEvaluations() {
  if (loadingMore.value) return
  
  loadingMore.value = true
  let params:any = {
    limit,
    offset: evaluations.value.length,
    filter: 1,
    gid: props.id
  }
  startRequest(RequestPath.evaluationListGet, 'get', params).then((response)=>{
    hasMore.value = (response.data.datas ?? []).length >= limit
    evaluations.value.push(...(response.data.datas as ExtendedEvaluationItemData[]));
  }).catch((_error)=>{
    // 错误处理
  }).finally(() => {
    loadingMore.value = false
  })
}

// 现有方法保持不变
onMounted(()=>{ 
    loadGoods()
    loadEvaluations()
})

function loadGoods() {
    startRequest(RequestPath.goodsGet, 'get', {id: props.id}).then((response)=>{
        goods.value = response.data.datas[0];
    }).catch((error)=>{
        ElMessage.error({
            message: error.response.data.error
        })
    })
}

function addToCar() {
    if (!account.isLogin) {
        ElMessage.warning('请先登录后再添加购物车')
        router.push({
            name: 'login'
        })
        return
    }
    
    let gid = goods.value.id
    let count = buyCount.value
    if (gid && count > 0) {
        startRequest(RequestPath.shopAdd, 'get', {gid, count}).then(()=>{
            ElMessage.success({
                message: "添加购物车成功"
            })
        }).catch((error)=>{
            ElMessage.error({
                message: error.response.data.error
            })
        })
    }
}
</script>

<style scoped>
.goods-detail-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  background: #fff;
  min-height: 100vh;
}

.breadcrumb {
  margin-bottom: 20px;
  padding: 10px 0;
}

.goods-main {
  display: flex;
  gap: 40px;
  margin-bottom: 40px;
}

/* 图片区域样式 */
.goods-gallery {
  flex: 0 0 450px;
}

.main-image {
  position: relative;
  width: 450px;
  height: 450px;
  border: 1px solid #f0f0f0;
  margin-bottom: 10px;
  overflow: hidden;
}

.goods-main-image {
  width: 100%;
  height: 100%;
}

.image-tag {
  position: absolute;
  top: 10px;
  left: 10px;
  padding: 4px 8px;
  border-radius: 2px;
  color: white;
  font-size: 12px;
}

.image-tag.hot {
  background: #ff4444;
}

.image-tag.new {
  background: #409eff;
}

/* 商品信息区域 */
.goods-info {
  flex: 1;
}

.goods-title {
  font-size: 20px;
  font-weight: 700;
  color: #333;
  margin-bottom: 10px;
}

.goods-desc {
  color: #999;
  font-size: 14px;
  margin-bottom: 20px;
}

/* 价格区域 */
.price-section {
  background: #f8f8f8;
  padding: 20px;
  border-radius: 6px;
  margin-bottom: 20px;
}

.current-price {
  display: flex;
  align-items: baseline;
  margin-bottom: 8px;
}

.price-label {
  color: #999;
  font-size: 14px;
  margin-right: 8px;
}

.price-symbol {
  color: #ff4444;
  font-size: 18px;
  font-weight: 700;
}

.price-number {
  color: #ff4444;
  font-size: 28px;
  font-weight: 700;
}

.original-price {
  color: #999;
  font-size: 14px;
  margin-bottom: 8px;
}

.line-through {
  text-decoration: line-through;
}

.save-amount {
  color: #ff4444;
  font-size: 14px;
}

/* 服务保障 */
.service-section {
  display: flex;
  gap: 20px;
  margin-bottom: 25px;
  padding-bottom: 20px;
  border-bottom: 1px solid #f0f0f0;
}

.service-item {
  display: flex;
  align-items: center;
  color: #666;
  font-size: 14px;
}

.service-icon {
  color: #409eff;
  margin-right: 4px;
}

/* 选择区域 */
.selection-section {
  margin-bottom: 25px;
}

.stock-info, .quantity-selector {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.stock-label, .quantity-label {
  width: 60px;
  color: #999;
  font-size: 14px;
}

.stock-count {
  color: #333;
  font-weight: 500;
}

.quantity-control {
  display: flex;
  align-items: center;
  gap: 15px;
}

.stock-tips {
  color: #999;
  font-size: 12px;
}

/* 操作按钮 */
.action-buttons {
  margin-bottom: 25px;
}

.btn-cart {
  width: 200px;
  height: 50px;
  font-size: 16px;
  background: #409eff;
  border-color: #409eff;
}

/* 促销信息 */
.promotion-section {
  border-top: 1px solid #f0f0f0;
  padding-top: 20px;
}

.promotion-title {
  color: #333;
  font-weight: 500;
  margin-bottom: 10px;
}

.promotion-item {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
  color: #666;
  font-size: 14px;
}

.promotion-tag {
  background: #ff4444;
  color: white;
  padding: 2px 6px;
  border-radius: 2px;
  font-size: 12px;
  margin-right: 8px;
}

/* 标签页区域 */
.goods-detail-tabs {
  margin-top: 40px;
  min-height: 600px;
}

.detail-tabs {
  background: #fff;
  min-height: 500px;
}

/* 详情内容区域 */
.detail-content {
  padding: 30px;
  min-height: 400px;
  background: #fafafa;
  border-radius: 8px;
}

.editor-content-view {
  line-height: 1.8;
  font-size: 14px;
  color: #333;
}

/* 评价区域 */
.evaluation-overview {
  display: flex;
  gap: 40px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 6px;
  margin-bottom: 20px;
}

.overview-item {
  text-align: center;
}

.overview-value {
  font-size: 24px;
  font-weight: 700;
  color: #ff4444;
  margin-bottom: 4px;
}

.overview-label {
  color: #999;
  font-size: 14px;
}

.evaluation-item {
  padding: 20px 0;
  border-bottom: 1px solid #f0f0f0;
}

.evaluation-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 10px;
}

.user-info {
  display: flex;
  align-items: flex-start;
  gap: 12px;
}

.user-avatar {
  background: #409eff;
}

.user-detail {
  flex: 1;
}

.username {
  color: #333;
  font-weight: 500;
  margin-bottom: 4px;
}

.evaluation-rate {
  line-height: 1;
}

.evaluation-time {
  color: #999;
  font-size: 12px;
}

.evaluation-content {
  color: #666;
  line-height: 1.6;
  margin-bottom: 10px;
}

.evaluation-actions {
  display: flex;
  gap: 20px;
}

.action-item {
  color: #999;
  font-size: 12px;
  cursor: pointer;
  transition: color 0.3s;
}

.action-item:hover {
  color: #409eff;
}

.load-more {
  text-align: center;
  padding: 20px;
}

/* 规格参数 */
.specs-section {
  padding: 30px;
  min-height: 300px;
}

.spec-item {
  display: flex;
  padding: 12px 0;
  border-bottom: 1px solid #f0f0f0;
}

.spec-label {
  width: 120px;
  color: #999;
  font-size: 14px;
}

.spec-value {
  color: #333;
  flex: 1;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .goods-main {
    flex-direction: column;
    gap: 20px;
  }
  
  .goods-gallery {
    flex: none;
  }
  
  .main-image {
    width: 100%;
    height: auto;
  }
  
  .btn-cart {
    width: 100%;
  }
  
  .detail-content {
    padding: 20px;
    min-height: 300px;
  }
}
</style>